package com.sun.controller;

import com.sun.model.Dept;
import com.sun.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept) {
        return deptService.add(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept getById(@PathVariable("id") Integer id) {
        return deptService.getById(id);
    }

    @GetMapping("/dept/getAll")
    public List<Dept> getAll() {
        return deptService.getDeptList();
    }

    /**
     * 注册的服务，可以获取相关的信息
     *
     * @return
     */
    @GetMapping("/dept/discover")
    public Object discover() {
        //获取服务清单列表
        List<String> services = discoveryClient.getServices();
        System.out.println("服务清单列表:" + services);
        //得到具体服务的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getInstanceId() + "\t"
                    + instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri());
        }

        return this.discoveryClient;
    }
}
